const request = require("request");
const axios = require("axios");
//消息模板
async function sendsubmit(code) {
  const config = {
    appid: "wx133bcd024fd764cd",
    secret: "23e95160b76e8a50a339f72a5a7adb4d",
  };
  // config.app.appid 对应小程序的appid
  // config.app.secret 对应小程序的秘钥
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.secret}`;
  const responses = await axios
    .get(url)
    .then(function (response) {
      // 处理成功情况
      return response.data;
    })
    .catch(function (error) {
      // 处理错误情况
      console.log(error);
    });
  console.log("222222", responses.access_token);

  const urlOpenid = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.appid}&secret=${config.secret}&js_code=${code}&grant_type=authorization_code`;
  console.log("appaid", urlOpenid);

  const responsesOpenid = await axios
    .get(urlOpenid)
    .then(function (response) {
      // 处理成功情况
      console.log("5555", response.data);

      return response.data;
    })
    .catch(function (error) {
      // 处理错误情况
      console.log(error);
    });

  // responses.access_token就是上一步我们拿到的access_token
  console.log("2222", responsesOpenid.openid);

  let messages = {
    touser: responsesOpenid.openid, //openid
    template_id: "N-mlkpSCtVRlgAmlnLpHhQu2aTi92MXH3VRyTHQaHeo", //订阅模板id
    miniprogram_state: "developer",
    access_token: responses.access_token,
    lang: "zh_CN",
    data: {
      thing1: {
        value: "日常消息",
      },
      thing6: {
        value: "公司发西瓜啦",
      },
      //留言内容
      thing2: {
        value: "请大家到四楼食堂领取西瓜",
      },
      //留言时间
      time3: {
        value: "2024-07-22 17:45:12",
      },
      //温馨提示
      thing9: {
        value: "陈超",
      },
    },
  };

  const urls = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${responses.access_token}`;

  const options = {
    method: "post",
    url: urls,
    json: messages, //第二步定于的消息内容
  };
  request(options, function (err, res, body) {
    if (err) {
      console.log(err);
    } else {
      if (body.errcode !== 0) {
        console.log(body);
      } else {
        console.log("发送成功");
      }
    }
  });
}

async function sendCode(req, res) {
  sendsubmit(req.body.Code);
}

module.exports = { sendCode };
